<?php
namespace addons\mall\controller;

use think\Config;
use think\Hook;
use think\Lang;

class Base extends \think\addons\Controller {
    public $session_id;
    public $cateTrre = array();

    // 模板配置信息
    protected $config = [
        'type'         => 'Think',
        'view_path'    => '',
        'view_suffix'  => 'html',
        'strip_space'  => true,
        'view_depr'    => DS,
        'tpl_begin'    => '{',
        'tpl_end'      => '}',
        'taglib_begin' => '{',
        'taglib_end'   => '}',
    ];
    
    // 初始化
    public function __construct()
    {
        parent::__construct();

        $config = get_addon_config('mall');
        $replace_str = config('view_replace_str');
        $replace_str =  array_merge($replace_str,$this->view->engine->config('tpl_replace_string'));
        $this->view->engine->config('tpl_replace_string',array_merge($replace_str,
            [
                '__STYLE__' => $config['theme'],
                '__MALLCDN__' => $config['mallcdn']?$config['mallcdn']:config('view_replace_str.__CDN__'),
            ]
        ));
        //渲染新的替换参数
        $this->config = array_merge($this->config, $this->view->engine->config('tpl_replace_string'));
        $this->config['user'] = $this->auth->isLogin() ? array_intersect_key($this->auth->getUserinfo(), array_flip(['id', 'username', 'nickname', 'avatar', 'score', 'money'])) : null;
        $this->view->assign('config', $this->config);

        // 设定主题模板目录
        $this->view->engine->config('view_path', $this->view->engine->config('view_path') . $config['theme'] . DS);
        // 加载自定义标签库
        $this->view->engine->config('taglib_pre_load', 'addons\mall\taglib\Mall');
        // 定义Mall首页的URL
        $config['indexurl'] = addon_url('mall/index/index', [], false);

        \think\Config::set("mall",$config);

        $this->assign("v",config('site.version')."_".config('site.homeStyleId'));
    }
    
    /**
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();

        // 语言检测
        $lang = strip_tags(Lang::detect());
        //上传配置
        $upload = \app\common\model\Config::upload();//读取系统上传配置
        Hook::listen("upload_config_init", $upload);//读取插件上传配置
        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 站点配置
        $site = Config::get("site");

        //配置设置：插件前端，借用系统前端目录存放js
        $this->config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages'])),
            'upload'         => $upload,
            //'addon'     => $this->addon,
            'modulename'     => $this->addon,
            'controllername' => $this->controller,
            'actionname'     => $this->action,
            'jsname'         => 'frontend/'.$this->addon.'/' . str_replace('.', '/', $this->controller),
            'moduleurl'      => rtrim(url("/index", '', false), '/'),
            'language'       => $lang
        ];
        $this->config = array_merge($this->config, $this->view->engine->config('tpl_replace_string'));

        Hook::listen("config_init", $this->config);

        // 渲染配置到视图中
        $this->config = array_merge($this->config, get_addon_config($this->addon));
        $this->view->assign("config", $this->config);

        // 加载当前控制器语言包
        $this->assign('site', $site);

        //如果登录的情况下
        if ($this->auth->isLogin()) {
            $user = $this->auth->getUser();
            $user->mall = \addons\mall\model\User::get($this->auth->id);

            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            $shop_id = \app\common\model\mall\shop\Shop::where("status","normal")->getFieldByUserId($this->auth->id,"id");
            cookie('shop_id', $shop_id, $expire);
            $this->view->assign('user', $user);
        }

        // 如果请求参数action的值为一个方法名,则直接调用
        $action = $this->request->post("action");
        if ($action && $this->request->isPost()) {
            return $this->$action();
        }
        //商品分类
        $sideCategorys = \app\common\model\mall\goods\Cat::getSideCategorys();
        $this->view->assign("sideCategorys", $sideCategorys);
        //帮助导航
        $catHelps = \app\common\model\mall\oper\Help::getCatHelps(4,6);
        $this->view->assign("catHelps", $catHelps);

    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed $searchfields 快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @param string $aliasName 关联查询的主表别名
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null, $aliasName = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        //如果是关联查询，则加上别名前缀（可在参数中指定主表别名）
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = $aliasName ? $aliasName : \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue 2;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue 2;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }

}